<?php
namespace bee;

function processForm()
{

  $cfg                         = config::getInstance();
  $app                         = app::getInstance();
  $app->addTimePoint("* start of process form");
  if(!owns_acces($app->getUser()->id, $app->getCurentForm()))
  { processor::getInstance()->denyUser();
  }
  $DSDoc                       = XMLDataHub::getInstance();
  $processor                   = new \XSLTProcessor();

  if($cfg->sys_XSL_PROFILING_DIR)
  { $processor->setProfiling($cfg->sys_XSL_PROFILING_DIR . date("Y-m-d-HIs") . ".txt");
  }

  $processor->registerPHPFunctions();
  $styleSheet                  = new \DOMDocument();

  $plugins                     = null;
  $disp                        = null;
  if($plugins_class_name       = $cfg->sys_PLUGINS_CLASS)
  {
    //echo "<br />PLUGIN CLASS NAME: $plugins_class_name : SESSION:" . session_id();
    $plugins = factory::load("bee_plugins_class");
    //echo "<br />FACTORY LOAD: " . print_r($plugins, true) . " :: ";
    if(!$plugins)
    {
      $plugins                 = $plugins_class_name::getInstance();
      //echo "<br />PLUGIN CREATE: " . print_r($plugins, true) . " :: ";
    } else
    {
      $plugins->setInstance($plugins);
      //echo "<br />PLUGIN LOAD: " . print_r($plugins, true) . " :: ";
      //$plugins                   = $plugins_class_name::getInstance();
    }
  }


  if($plugins)
  { $disp                      = dispatcher::getInstance();
    $disp->addObject($plugins);
    $disp->dispatch("preProcess");
  }



  $DSDoc->setVariable(  "app_TIME",           date( "d.m.Y H:i:s"));
  $DSDoc->setVariable(  "app_USERNAME",       $app->getUser()->login);
  $DSDoc->setVariable(  "app_USERID",         $app->getUser()->id);
  $DSDoc->setVariable(  "sys_generate_XML",   $cfg->sys_generate_XML);
  $DSDoc->setVariable(  "sys_page",           $app->activeMenu);
  $DSDoc->setVariable(  "sys_action",         $app->request->getField("sys_action"));
  $DSDoc->setVariable(  "sys_kom_filter",     $app->getClientFilter());
  $DSDoc->setVariable(  "sys_CSS_STYLE",      $cfg->sys_CSS_STYLE);
  $DSDoc->setVariable(  "APPLICATION_TITLE",  $cfg->app_APPLICATION_TITLE);
  $DSDoc->setVariable(  "site_status",        $cfg->site_status);

  $DSDoc->setArray($_REQUEST, "__request");

  if($plugins)
  { $disp->dispatch("preForm");
  }


  $app->addTimePoint("* after preform");

  $form_name = $app->getCurentForm();

  $noLoad = false;
  if((isset($_REQUEST["__noload"]) ? $_REQUEST["__noload"] : "false") == "true")
  { $noLoad = true;
  }

  //$form = call_user_func(array($form_name , "getInstance"), $noLoad);

  $form = $form_name::getInstance($noLoad);

  $app->addTimePoint("* before postform");

  if($plugins)
  { $disp->dispatch("postForm");
  }

  $DSDoc->setVariable(  "sys_php_last_time", date("ymdhi", filemtime($cfg->sys_USR_APP_PATH . "/" . $app->getCurentForm() . ".php")) );
  $DSDoc->setVariable(  "sys_frm_last_time", date("ymdhi", filemtime($cfg->sys_TEMPLATE_PATH . "/" . $app->getCurentForm() . ".xsl")));
  $DSDoc->setVariable(  "app_HEADLINE",     $form->__caption);
  $DSDoc->setVariable(  "app_META_DESC",     $form->__meta_desc);
  $DSDoc->setVariable(  "sys_frm_version",  $form->__version);

  $DSDoc->setVariable(  "sys_msg_style",    ($app->getMessageLevel() != "normal") ? $app->getMessageLevel() : "");
  //die($app->getMessageText());
  $DSDoc->setVariable(  "sys_msg",          $app->getMessageText());

  if($form->getParent());
  { $DSDoc->setVariable("__frm_back", $form->getParent());
  }

  /**
   *@todo state is probably deprecated

   if(isset($sys_stateID))
   { $DSDoc->setVariable("sys_stateID",      $sys_stateID);
   }
   */

  //echo "(" . $app->getTemplate() . ")";
  $styleSheet->load($cfg->sys_TEMPLATE_PATH . "/" . $app->getTemplate());
  $main                        = $styleSheet->getElementsByTagName("call-template");
  foreach ($main as $child)
  {
    if($child->getAttribute("name") == "zamijeni-me-php")
    {
      $child->setAttribute("name", $app->getCurentForm());
    }
  }

  $main                        = $styleSheet->getElementsByTagName("include");
  foreach ($main as $child)
  {
    if($child->getAttribute("href") == "zamijeni-me-php")
    {
      $child->setAttribute("href", $app->getCurentForm() . ".xsl");
    }
  }





  $processor->importStylesheet($styleSheet);
  $processor->setParameter("", "__form", isset(app::$activeMenu) ? app::$activeMenu : $app->getCurentForm());
  $processor->setParameter("", "sys_action", isset($_REQUEST["sys_action"]) ? $_REQUEST["sys_action"] : "");

  $jqTxt                       = "";
  //global $t;
  //echo "(pT " . (microtime(true) - $t) . ")";
  $app->tmpDoc                 = $processor->transformToDoc($DSDoc);
  //echo "(PT " . (microtime(true) - $t) . ")";
  $tmpDoc                      = $app->tmpDoc;
  $xpath                       = new \DOMXPath($DSDoc);
  $domNList                    = $xpath->query("/form/widgets");
  $widgets                     = simplexml_import_dom($domNList->item(0));
  $regionals                   = array();

//   foreach ($widgets->children() as $widget)
//   { if($widget->widgetType == 1)
//     { $completers = $widget->autoComplete->children();
//       if( $completers->count() > 0)
//       { if($widget->autoComplete->source->value->count() > 1)
//         { $jsArrString = "";
//           foreach($widget->autoComplete->source->value as $val)
//           { if($jsArrString)
//             { $jsArrString     .= "', '" . $val;
//             } else
//             { $jsArrString    = "['" . $val;
//             }
//           }
//           $jsArrString .= "']";
//         } else
//         { $jsArrString = "'index.php?__ajax=&sys_action=" . $widget->autoComplete->source . "'";
//         }
//         if($widget->autoComplete->minLength > 0)
//         { $ml = ", minLength: " . $widget->autoComplete->minLength;
//         }  else
//         {  $ml = "";
//         }
//         //---------------------------8<-----------
//         $jqTxt .= "\t\t$('#" . $widget->id .
//         "').autocomplete({source: " . $jsArrString . $ml . " });\n\t\t$('#" . $widget->id .
//         "').live('focus', function(){\n\t\t$('#" . $widget->id .
//         "').autocomplete({source: " . $jsArrString . $ml . "});})\n";
//         //--------------------------->8------------*/
//       }
//     }
//   }

//   $script                      = $tmpDoc->createElement("script", "$(document).ready(function(){\n"
//       . $jqTxt . "})");
//   $script->setAttribute("language", "javascript");
//   $tmpDoc->appendChild($script);
  $regionals                   = array_unique($regionals);
  foreach ($regionals as $value)
  { $script                    = $tmpDoc->createElement("script");
    $script->setAttribute("type", "text/javascript");
    $script->setAttribute("src", "test/jquery-ui-1.8.7.custom/development-bundle/ui/i18n/jquery.ui.datepicker-" . $value . ".js");
    $tmpDoc->appendChild($script);
  }

  if($plugins && $plugins->isDebugMode || $cfg->sys_IS_DEBUG_MODE)
  { $DSDoc->setVariable("sys_DEBUG_INFO", $app->getDebug());
  }
  if($app->getCurentForm() && $cfg->sys_generate_XML)
  {
    $DSDoc->save($cfg->sys_TMP_PATH. "/" . $app->getCurentForm() . ".xml" );//****
  }
  $form->cleanUp();
  $db = db::getInstance();
  $db->cleanUp();

  factory::save($form, $form_name::getFormID());//------------------->

  //$app->echo = $tmpDoc->saveHTML();//$tmpDoc->documentElement
  $app->echo = $tmpDoc->saveHTML($tmpDoc->documentElement);//
  $app->addTimePoint("* end of processForm");
  if($plugins)
  { $disp->dispatch("postProcess");
    //echo "<br />PLUGIN SAVE: " . print_r($plugins, true) . " / " . factory::save($plugins, "bee_plugins_class") . " ::";
    factory::save($plugins, "bee_plugins_class");
  }
  //echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">'. "\n" . $app->echo;

  echo "<!DOCTYPE html>\n" . $app->echo;
  //echo $app->echo;


  //echo "!!" . $app->getUser()->id . "!!";
//die("ee");
  //echo "<br />P: " . memory_get_peak_usage(true) ." / " .  memory_get_peak_usage(false) ;
}
